package com.wormhole.wormholemanagement.utils;

import com.wormhole.wormholemanagement.dto.DocumentNode;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;

public class FileSystemUtils {

    public static DocumentNode buildDocumentTree(String rootPath) throws IOException {
        Path root = Paths.get(rootPath);
        if (!Files.exists(root)) {
            throw new IllegalArgumentException("目录不存在: " + rootPath);
        }

        return buildTree(root, root);
    }

    private static DocumentNode buildTree(Path root, Path current) throws IOException {
        String name = current.getFileName().toString();
        String relativePath = root.relativize(current).toString();
        boolean isDirectory = Files.isDirectory(current);

        DocumentNode node = new DocumentNode(name, relativePath, isDirectory);

        if (isDirectory) {
            // 遍历目录并按文件名排序
            Files.list(current)
                    .sorted(Comparator.comparing(path -> path.getFileName().toString()))
                    .forEach(path -> {
                        try {
                            DocumentNode child = buildTree(root, path);
                            node.getChildren().add(child);
                        } catch (IOException e) {
                            // 处理异常或跳过
                        }
                    });
        }

        return node;
    }
}